<?php
namespace Emos\Db;

class Pdo extends AbstractAdapter { 
    public function connect($params) {                
        $params = array(            
            'charset'   => 'utf8',
            'user'      => 'root',
            'password'  => '',            
        ) + $params;       
                
        try {
            $this->connection = new \PDO($params['dsn'], $params['user'], $params['password']);                        
            $this->connection->query('SET CHARACTER SET '.$params['charset']);        
        }
        catch(Db\Exception $ex) {
            throw new Exception("Can not connect to database '".$params['base']."': ".$ex->getMessage());            
        }
    }
    
    function selectQuery($sql) {        
		$stmt = $this->connection->query($sql);
        if($this->connection->errorCode() != \PDO::ERR_NONE) {
            throw new Exception("SQL query error: {$sql}", $sql);            
        }         
        
        $data = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        $stmt->closeCursor();
        return $data;        
    }
    
    function execQuery($sql) {        
		$stmt = $this->connection->query($sql);
        if($this->connection->errorCode() != \PDO::ERR_NONE) {
            throw new Exception("SQL query error: {$sql}", $sql);            
        } 
        
        return $stmt->rowCount();
    }    
    
    function getInsertId() {
        return $this->connection->lastInsertId();
    }
}
